/**
 * 通知API库
 * @author HalRui
 * @version 1.0.0
 * @description 提供通知相关的业务逻辑处理，包括通知创建、查询、已读管理、系统通知、批量操作等功能
 * @date 2025年9月27日
 */

const Notifications = require('../models/notifications-model');
const UserInfos = require('../models/userinfos-model');
const Videos = require('../models/videos-model');

/**
 * 创建通知
 * @param {Object} notificationData - 通知数据
 * @returns {Promise<Object>} 创建结果
 */
async function createNotification(notificationData) {
    try {
        const { userId, fromUserId } = notificationData;
        
        // 验证用户是否存在
        const user = await UserInfos.findOne({ userId, isDeleted: false });
        if (!user) {
            return {
                success: false,
                message: '目标用户不存在'
            };
        }
        
        // 验证发送者是否存在（如果有）
        if (fromUserId) {
            const fromUser = await UserInfos.findOne({ userId: fromUserId, isDeleted: false });
            if (!fromUser) {
                return {
                    success: false,
                    message: '发送者用户不存在'
                };
            }
        }
        
        // 检查是否为自己发送给自己的通知（某些类型需要过滤）
        if (fromUserId && userId === fromUserId) {
            const skipTypes = ['like', 'comment', 'reply', 'follow', 'favorite'];
            if (skipTypes.includes(notificationData.type)) {
                return {
                    success: false,
                    message: '不能给自己发送此类型通知'
                };
            }
        }
        
        const notification = await Notifications.createNotification(notificationData);
        
        return {
            success: true,
            data: notification,
            message: '通知创建成功'
        };
    } catch (error) {
        console.error('创建通知失败:', error);
        return {
            success: false,
            message: '创建通知失败',
            error: error.message
        };
    }
}

/**
 * 批量创建通知
 * @param {Array} notificationsData - 通知数据数组
 * @returns {Promise<Object>} 创建结果
 */
async function createBatchNotifications(notificationsData) {
    try {
        // 验证所有用户是否存在
        const userIds = [...new Set(notificationsData.map(n => n.userId))];
        const users = await UserInfos.find({ 
            userId: { $in: userIds }, 
            isDeleted: false 
        }).select('userId');
        
        const existingUserIds = new Set(users.map(u => u.userId));
        const validNotifications = notificationsData.filter(n => existingUserIds.has(n.userId));
        
        if (validNotifications.length === 0) {
            return {
                success: false,
                message: '没有有效的用户'
            };
        }
        
        const notifications = await Notifications.createBatchNotifications(validNotifications);
        
        return {
            success: true,
            data: notifications,
            message: `成功创建 ${notifications.length} 条通知`,
            skipped: notificationsData.length - validNotifications.length
        };
    } catch (error) {
        console.error('批量创建通知失败:', error);
        return {
            success: false,
            message: '批量创建通知失败',
            error: error.message
        };
    }
}

/**
 * 获取用户通知列表
 * @param {Object} options - 查询选项
 * @returns {Promise<Object>} 通知列表
 */
async function getUserNotifications(options) {
    try {
        const { userId } = options;
        
        // 验证用户是否存在
        const user = await UserInfos.findOne({ userId, isDeleted: false });
        if (!user) {
            return {
                success: false,
                message: '用户不存在'
            };
        }
        
        const result = await Notifications.getUserNotifications(options);
        
        // 获取发送者用户信息
        const fromUserIds = [...new Set(result.notifications
            .filter(n => n.fromUserId)
            .map(n => n.fromUserId))];
        
        let fromUsers = {};
        if (fromUserIds.length > 0) {
            const users = await UserInfos.find({ 
                userId: { $in: fromUserIds }, 
                isDeleted: false 
            }).select('userId username avatar');
            
            fromUsers = users.reduce((acc, user) => {
                acc[user.userId] = {
                    userId: user.userId,
                    username: user.username,
                    avatar: user.avatar
                };
                return acc;
            }, {});
        }
        
        // 添加发送者信息
        const notificationsWithUsers = result.notifications.map(notification => ({
            ...notification,
            fromUser: notification.fromUserId ? fromUsers[notification.fromUserId] || null : null
        }));
        
        return {
            success: true,
            data: {
                ...result,
                notifications: notificationsWithUsers
            },
            message: '获取通知列表成功'
        };
    } catch (error) {
        console.error('获取用户通知列表失败:', error);
        return {
            success: false,
            message: '获取通知列表失败',
            error: error.message
        };
    }
}

/**
 * 获取通知详情
 * @param {number} notificationId - 通知ID
 * @param {number} userId - 用户ID
 * @returns {Promise<Object>} 通知详情
 */
async function getNotificationDetail(notificationId, userId) {
    try {
        const notification = await Notifications.findOne({
            notificationId,
            userId,
            isDeleted: false
        });
        
        if (!notification) {
            return {
                success: false,
                message: '通知不存在'
            };
        }
        
        // 获取发送者信息
        let fromUser = null;
        if (notification.fromUserId) {
            const user = await UserInfos.findOne({ 
                userId: notification.fromUserId, 
                isDeleted: false 
            }).select('userId username avatar');
            
            if (user) {
                fromUser = {
                    userId: user.userId,
                    username: user.username,
                    avatar: user.avatar
                };
            }
        }
        
        // 获取目标信息
        let target = null;
        if (notification.targetType && notification.targetId) {
            if (notification.targetType === 'video') {
                const video = await Videos.findOne({ 
                    videoID: notification.targetId, 
                    isDeleted: false 
                }).select('videoID title coverImage');
                
                if (video) {
                    target = {
                        type: 'video',
                        id: video.videoID,
                        title: video.title,
                        coverImage: video.coverImage
                    };
                }
            } else if (notification.targetType === 'user') {
                const user = await UserInfos.findOne({ 
                    userId: notification.targetId, 
                    isDeleted: false 
                }).select('userId username avatar');
                
                if (user) {
                    target = {
                        type: 'user',
                        id: user.userId,
                        username: user.username,
                        avatar: user.avatar
                    };
                }
            }
        }
        
        const notificationData = notification.getSafeJSON();
        
        return {
            success: true,
            data: {
                ...notificationData,
                fromUser,
                target
            },
            message: '获取通知详情成功'
        };
    } catch (error) {
        console.error('获取通知详情失败:', error);
        return {
            success: false,
            message: '获取通知详情失败',
            error: error.message
        };
    }
}

/**
 * 标记通知为已读
 * @param {Object} options - 标记选项
 * @returns {Promise<Object>} 标记结果
 */
async function markNotificationsAsRead(options) {
    try {
        const { userId } = options;
        
        // 验证用户是否存在
        const user = await UserInfos.findOne({ userId, isDeleted: false });
        if (!user) {
            return {
                success: false,
                message: '用户不存在'
            };
        }
        
        const result = await Notifications.markAsRead(options);
        
        return {
            success: true,
            data: result,
            message: `成功标记 ${result.modifiedCount} 条通知为已读`
        };
    } catch (error) {
        console.error('标记通知为已读失败:', error);
        return {
            success: false,
            message: '标记通知为已读失败',
            error: error.message
        };
    }
}

/**
 * 删除通知
 * @param {Object} options - 删除选项
 * @returns {Promise<Object>} 删除结果
 */
async function deleteNotifications(options) {
    try {
        const { userId } = options;
        
        // 验证用户是否存在
        const user = await UserInfos.findOne({ userId, isDeleted: false });
        if (!user) {
            return {
                success: false,
                message: '用户不存在'
            };
        }
        
        const result = await Notifications.deleteNotifications(options);
        
        return {
            success: true,
            data: result,
            message: `成功删除 ${result.modifiedCount} 条通知`
        };
    } catch (error) {
        console.error('删除通知失败:', error);
        return {
            success: false,
            message: '删除通知失败',
            error: error.message
        };
    }
}

/**
 * 获取未读通知数量
 * @param {number} userId - 用户ID
 * @param {string} [type] - 通知类型
 * @returns {Promise<Object>} 未读数量
 */
async function getUnreadCount(userId, type = null) {
    try {
        // 验证用户是否存在
        const user = await UserInfos.findOne({ userId, isDeleted: false });
        if (!user) {
            return {
                success: false,
                message: '用户不存在'
            };
        }
        
        const count = await Notifications.getUnreadCount(userId, type);
        
        return {
            success: true,
            data: { count },
            message: '获取未读通知数量成功'
        };
    } catch (error) {
        console.error('获取未读通知数量失败:', error);
        return {
            success: false,
            message: '获取未读通知数量失败',
            error: error.message
        };
    }
}

/**
 * 获取通知统计
 * @param {number} userId - 用户ID
 * @returns {Promise<Object>} 通知统计
 */
async function getNotificationStats(userId) {
    try {
        // 验证用户是否存在
        const user = await UserInfos.findOne({ userId, isDeleted: false });
        if (!user) {
            return {
                success: false,
                message: '用户不存在'
            };
        }
        
        const stats = await Notifications.getNotificationStats(userId);
        
        return {
            success: true,
            data: stats,
            message: '获取通知统计成功'
        };
    } catch (error) {
        console.error('获取通知统计失败:', error);
        return {
            success: false,
            message: '获取通知统计失败',
            error: error.message
        };
    }
}

/**
 * 获取系统通知
 * @param {Object} options - 查询选项
 * @returns {Promise<Object>} 系统通知列表
 */
async function getSystemNotifications(options) {
    try {
        const result = await Notifications.getSystemNotifications(options);
        
        return {
            success: true,
            data: result,
            message: '获取系统通知成功'
        };
    } catch (error) {
        console.error('获取系统通知失败:', error);
        return {
            success: false,
            message: '获取系统通知失败',
            error: error.message
        };
    }
}

/**
 * 发送系统广播通知
 * @param {Object} notificationData - 通知数据
 * @param {Array} userIds - 用户ID数组
 * @returns {Promise<Object>} 发送结果
 */
async function broadcastSystemNotification(notificationData, userIds) {
    try {
        // 验证用户是否存在
        const users = await UserInfos.find({ 
            userId: { $in: userIds }, 
            isDeleted: false 
        }).select('userId');
        
        const existingUserIds = users.map(u => u.userId);
        
        if (existingUserIds.length === 0) {
            return {
                success: false,
                message: '没有有效的用户'
            };
        }
        
        const notifications = await Notifications.broadcastSystemNotification(
            notificationData, 
            existingUserIds
        );
        
        return {
            success: true,
            data: notifications,
            message: `成功发送系统通知给 ${existingUserIds.length} 个用户`,
            skipped: userIds.length - existingUserIds.length
        };
    } catch (error) {
        console.error('发送系统广播通知失败:', error);
        return {
            success: false,
            message: '发送系统广播通知失败',
            error: error.message
        };
    }
}

/**
 * 创建点赞通知
 * @param {number} fromUserId - 点赞用户ID
 * @param {number} toUserId - 被点赞用户ID
 * @param {number} videoId - 视频ID
 * @returns {Promise<Object>} 创建结果
 */
async function createLikeNotification(fromUserId, toUserId, videoId) {
    try {
        // 获取视频信息
        const video = await Videos.findOne({ 
            videoID: videoId, 
            isDeleted: false 
        }).select('title');
        
        if (!video) {
            return {
                success: false,
                message: '视频不存在'
            };
        }
        
        // 获取点赞用户信息
        const fromUser = await UserInfos.findOne({ 
            userId: fromUserId, 
            isDeleted: false 
        }).select('username');
        
        if (!fromUser) {
            return {
                success: false,
                message: '用户不存在'
            };
        }
        
        const notificationData = {
            userId: toUserId,
            type: 'like',
            title: '收到新的点赞',
            content: `${fromUser.username} 点赞了你的视频《${video.title}》`,
            data: {
                videoId,
                videoTitle: video.title
            },
            fromUserId,
            targetType: 'video',
            targetId: videoId
        };
        
        return await createNotification(notificationData);
    } catch (error) {
        console.error('创建点赞通知失败:', error);
        return {
            success: false,
            message: '创建点赞通知失败',
            error: error.message
        };
    }
}

/**
 * 创建评论通知
 * @param {number} fromUserId - 评论用户ID
 * @param {number} toUserId - 被评论用户ID
 * @param {number} videoId - 视频ID
 * @param {number} commentId - 评论ID
 * @param {string} content - 评论内容
 * @returns {Promise<Object>} 创建结果
 */
async function createCommentNotification(fromUserId, toUserId, videoId, commentId, content) {
    try {
        // 获取视频信息
        const video = await Videos.findOne({ 
            videoID: videoId, 
            isDeleted: false 
        }).select('title');
        
        if (!video) {
            return {
                success: false,
                message: '视频不存在'
            };
        }
        
        // 获取评论用户信息
        const fromUser = await UserInfos.findOne({ 
            userId: fromUserId, 
            isDeleted: false 
        }).select('username');
        
        if (!fromUser) {
            return {
                success: false,
                message: '用户不存在'
            };
        }
        
        const notificationData = {
            userId: toUserId,
            type: 'comment',
            title: '收到新的评论',
            content: `${fromUser.username} 评论了你的视频《${video.title}》：${content.substring(0, 50)}${content.length > 50 ? '...' : ''}`,
            data: {
                videoId,
                videoTitle: video.title,
                commentId,
                commentContent: content
            },
            fromUserId,
            targetType: 'video',
            targetId: videoId
        };
        
        return await createNotification(notificationData);
    } catch (error) {
        console.error('创建评论通知失败:', error);
        return {
            success: false,
            message: '创建评论通知失败',
            error: error.message
        };
    }
}

/**
 * 创建关注通知
 * @param {number} fromUserId - 关注用户ID
 * @param {number} toUserId - 被关注用户ID
 * @returns {Promise<Object>} 创建结果
 */
async function createFollowNotification(fromUserId, toUserId) {
    try {
        // 获取关注用户信息
        const fromUser = await UserInfos.findOne({ 
            userId: fromUserId, 
            isDeleted: false 
        }).select('username');
        
        if (!fromUser) {
            return {
                success: false,
                message: '用户不存在'
            };
        }
        
        const notificationData = {
            userId: toUserId,
            type: 'follow',
            title: '收到新的关注',
            content: `${fromUser.username} 关注了你`,
            data: {
                followerId: fromUserId,
                followerUsername: fromUser.username
            },
            fromUserId,
            targetType: 'user',
            targetId: fromUserId
        };
        
        return await createNotification(notificationData);
    } catch (error) {
        console.error('创建关注通知失败:', error);
        return {
            success: false,
            message: '创建关注通知失败',
            error: error.message
        };
    }
}

module.exports = {
    createNotification,
    createBatchNotifications,
    getUserNotifications,
    getNotificationDetail,
    markNotificationsAsRead,
    deleteNotifications,
    getUnreadCount,
    getNotificationStats,
    getSystemNotifications,
    broadcastSystemNotification,
    createLikeNotification,
    createCommentNotification,
    createFollowNotification
};